import React from 'react'
import { Icon } from 'antd';
import Pop from './Pop'
import moment from 'moment'
import './index.less'
const shallowequal = require('shallowequal');
export default class YearPickerRange extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      isopen: false,
      popPositionLeft: true,
      propsValue: props.value,
      propsRange: props.range, // 用作比较
      value: props.value || ['', ''], // 默认没有值，数据格式不能变
      range: props.range || ['', '']
    }
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    if (!shallowequal(nextProps.value, prevState.propsValue)) {
      // console.log(nextProps.value, 333)
      return {
        ...prevState,
        propsValue: nextProps.value,
        value: nextProps.value || ['', '']
      }
    }
    return null
  }

  closePop = () => {
    this.setState({
      isopen: false
    })
  }
  handleOpen = async(event) => {
    event.persist();
    await this.setState({
      isopen: true,
      popPositionLeft: event.clientX< document.body.clientWidth/2
    });
  }

  // 确认时候关闭弹出框
  handleSure = value => {
    this.setState({
      value,
      isopen: false
    }, () => {
      // 确认日期的时候调用的函数，也可作为日期的双向绑定
      if (this.props.handleSure) {
        this.props.handleSure(value)
      }
    })
  }

  render() {
    const { popPositionLeft } = this.state;
    return (
      <span className="pickwrap"
        style={this.props.style}
      >
        <span className="inputSpan"
          onClick={this.handleOpen}
        >
          <span className="innerSpan">
            <Icon className="i-left"
              type="schedule"
            />
            <input placeholder="开始日期"
              readOnly
              value={this.state.value[0]}
            />
            <span>~</span>
            <input placeholder="结束日期"
              readOnly
              value={this.state.value[1]}
            />
            <Icon className="i-right"
              type="caret-down"
            />
          </span>
        </span>
        {
          (() => {
            if(this.state.isopen){
              return <Pop closePop={this.closePop.bind(this)}
                handleSure={this.handleSure.bind(this)}
                popPositionLeft={popPositionLeft}
                range={this.state.range}
                value={this.state.value}
              />
            }
          })()
        }
      </span>
    )
  }
}